package servlet;

import java.io.*;
import java.sql.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;

import util.*;
import bll.*;
import model.*;
import dal.*;

/**
 * Servlet implementation class CompanyServlet
 */
@WebServlet(urlPatterns = { "/ClickAndSave", "/clickAndSave", "/ClickAndSaveServlet", "/clickAndSaveServlet" }, initParams = { @WebInitParam(name = "mode", value = "") })
public class ClickAndSaveServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public ClickAndSaveServlet() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/xml; charset=UTF-8");

		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		
		// TODO read from URL param
		String table = "";
		String field = "";
		String success="1";
		String mode = request.getParameter("mode");
		
		if (mode.equalsIgnoreCase("click")) {
			String id = request.getParameter("id");
			System.out.print("id: "+id);
			String old = request.getParameter("old");
			System.out.print("  old value: "+old);	
			String value = request.getParameter("value");
			System.out.print("   value: "+value);	  
			if(value.isEmpty()||value==null)
				success="0";
			
			System.out.println("  success: "+success);	 
			JSONObject json = new JSONObject();
			json.put("id", id);
			json.put("success", success);
			json.put("old", old);

			PrintWriter out = response.getWriter();
			
			out.print(json);
		}
		
	}
}